package xin.yangshuai.oauth201.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import xin.yangshuai.common01.entity.AuthorizationInfo;
import xin.yangshuai.oauth201.config.PasswordCredentialsConfig;

@Controller
@RequestMapping("passwordCredentials")
public class PasswordCredentialsController {

    public static final Logger logger = LoggerFactory.getLogger(PasswordCredentialsController.class);

    @Autowired
    private PasswordCredentialsConfig passwordCredentialsConfig;

    @RequestMapping("redirect")
    @ResponseBody
    public AuthorizationInfo redirect() {

        String accessTokenUrl = passwordCredentialsConfig.getAccessTokenUrl();
        String clientId = passwordCredentialsConfig.getClientId();
        String clientSecret = passwordCredentialsConfig.getClientSecret();
        String username = passwordCredentialsConfig.getUsername();
        String password = passwordCredentialsConfig.getPassword();

        logger.info("access_token_url=[{}]", accessTokenUrl);
        logger.info("client_id=[{}]", clientId);
        logger.info("client_secret=[{}]", clientSecret);
        logger.info("username=[{}]", username);
        logger.info("password=[{}]", password);

        RestTemplate restTemplate = new RestTemplate();
        AuthorizationInfo authorizationInfo = restTemplate.getForObject(accessTokenUrl + "?clientId=" + clientId + "&clientSecret=" + clientSecret + "&username=" + username + "&password=" + password + "&grantType=password", AuthorizationInfo.class);

        return authorizationInfo;
    }
}
